﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using CSP.Common.Factories;
using CSP.Common.Providers;
using CSP.Common.Web;
using CSP.Common.Tools;
using System.Collections;
using CSP.Model.CSP;
using CSP.Model.CSPEnum;

namespace CSP.Web.UserControls
{
    public partial class CSPUpload : CSPUserControlBase
    {
        /// <summary>
        /// 临时文件夹路径
        /// </summary>
        private const string TEM_FILEPATH = "/Upload/Tmp/";

        /// <summary>
        /// 发布文件夹路径
        /// </summary>
        private const string RELEASE_FILEPATH = "/Upload/";

        /// <summary>
        /// 是否将图片从临时文件夹中提取到发布文件夹中，默认False
        /// </summary>
        private bool _isReleaseImg = false;

        private string[] _totalImgURL = new string[0];

        private string _currentPagePath;

        /// <summary>
        /// 当前承载页面的路径
        /// </summary>
        public string CurrentPagePath
        {
            get
            {
                return _currentPagePath;
            }
        }

        private Dictionary<int, string> _setImageURL = new Dictionary<int, string>();

        /// <summary>
        /// 设置生成控件时的图片信息 key 为Id,value 为URL(URL必须为S_开头的缩略图路径)
        /// </summary>
        public Dictionary<int, string> SetImageURL
        {
            set
            {
                _setImageURL = value;
            }
        }

        /// <summary>
        /// 需要的新Img信息
        /// </summary>
        public string[] NewImageURLs
        {
            get
            {
                //如果图片已经转移到发布文件夹中
                if (_isReleaseImg)
                {
                    if (string.IsNullOrWhiteSpace(this.Txt_ImgURL_Insert.Value))
                    {
                        return new string[0];
                    }
                    return this.Txt_ImgURL_Insert.Value.Replace(TEM_FILEPATH + "image", "/Upload").Replace("S_", "").Split('|');
                }
                else if (string.IsNullOrWhiteSpace(this.Txt_ImgURL_Insert.Value))
                {
                    return new string[0];

                }
                else 
                {
                    return this.Txt_ImgURL_Insert.Value.Split('|');
                }
            }
        }

        public int[] DeleteImageIds
        {
            get
            {
                int[] imgIds = new int[0];
                if (this.Txt_ImgURL_Delete.Value == "")
                {
                    return imgIds;
                }
                string[] temImgIds = this.Txt_ImgURL_Delete.Value.Split('|');
                imgIds = (from img in temImgIds
                          select Convert.ToInt32(img)).ToArray();

                return imgIds;
            }
        }

        private string _imageObjs;

        /// <summary>
        /// 图片的json对象
        /// </summary>
        protected string ImageObjs
        {
            get
            {
                return _imageObjs;
            }
        }

        /// <summary>
        /// 当程序未初始化控件时加载
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (this.Page.Request["CSPUpload"] != null)
            {
                Upload_Request();
            }
            else if (this.Page.Request["CSPUpload_DeleteURL"] != null)
            {
                DeleteImg();
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            _currentPagePath = this.Page.Request.Path;
            InitImg();
        }

        private void InitImg()
        {
            if (_setImageURL.Count == 0)
            {
                _imageObjs = "null";
            }
            else
            {
                _imageObjs = "";

                List<UpLoadImage> uploadImages = new List<UpLoadImage>();
                foreach (var key in _setImageURL.Keys)
                {
                    UpLoadImage uploadImage = new UpLoadImage
                    {
                        Id = key,
                        Url = _setImageURL[key]
                    };
                    uploadImages.Add(uploadImage);
                }

                _imageObjs = CommonTool.SerializeObject(uploadImages);
            }

        }

        public void RemoveImages(ServiceImage[] serviceImages)
        {
            for (int i = 0; i < serviceImages.Length;i++ )
            {
                if (serviceImages[i].ImageOperateSatus == ImageOperateSatus.Deleted)
                {
                    string imgThumbnailURL = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + serviceImages[i].FilePath + serviceImages[i].FileName;
                    string imgURL = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + serviceImages[i].FilePath +"S_"+ serviceImages[i].FileName;
                    File.Delete(imgThumbnailURL);
                    File.Delete(imgURL);
                }
            }
        }

        /// <summary>
        /// 删除图片
        /// </summary>
        private void DeleteImg()
        {
            string imgThumbnailURL = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @Page.Request["CSPUpload_DeleteURL"].ToString().Substring(1);
            string imgURL = imgThumbnailURL.Replace("S_", "");
            try
            {
                //File.
                File.Delete(imgThumbnailURL);
                File.Delete(imgURL);
            }
            catch (Exception ex)
            {
                LoggerFactory.GetErrorLogger().Error("文件删除失败!" + imgURL, ex);
            }
            Response.ClearContent();
            Response.Write("{\"status\":1,\"msg\":\"操作成功!\"}");
            Response.End();
        }


        /// <summary>
        /// 根据URL 获取排序Id
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public int GetOrderId(string url)
        {
            int result = -1;
            for (int i = 0; i < _totalImgURL.Length; i++)
            {
                if (_totalImgURL[i] == url)
                {
                    result = i + 1;
                    return result;
                }
            }

            return result;
        }

        /// <summary>
        /// 将图片从临时文件夹中提取到发布文件夹中
        /// </summary>
        public void ReleaseImg()
        {
            string imgReleasingURl = this.Txt_ImgURL_Insert.Value;
            if (Txt_ImgURL_Total.Value.Length!=0)
            {
                _totalImgURL = Txt_ImgURL_Total.Value.Trim().Split('|');
            }
            
            if (!string.IsNullOrWhiteSpace(imgReleasingURl))
            {
                string[] imgURLs = imgReleasingURl.Split('|');
                string imgURL = "";
                for (int i = 0; i < imgURLs.Length; i++)
                {
                    imgURL = imgURLs[i];
                    MoveFile(imgURL);
                }

                //发布处理总Image的URL
                _totalImgURL = Txt_ImgURL_Total.Value.Replace("S_", "").Replace(TEM_FILEPATH + "image", "/Upload").Split('|');
            }

            _isReleaseImg = true;
        }

        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="url"></param>
        private void MoveFile(string url)
        {
            string domainURL = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            string fileNames = "/" + @url.Substring(1);
            url = domainURL + @url.Substring(1);
            string[] partPathes = fileNames.Replace(TEM_FILEPATH + "image/", "").Replace("S_", "").Split('/');

            string directory = domainURL + @RELEASE_FILEPATH.Substring(1) + partPathes[0];
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            string releaseURL = directory + "/" + partPathes[1];
            string releaseThumbnailURL = directory + "/" + "S_" + partPathes[1];
            File.Move(url.Replace("S_", ""), releaseURL);
            File.Move(url, releaseThumbnailURL);
        }

        private void Upload_Request()
        {
            HttpPostedFile file = Request.Files["FileData"];
            ImageProviderFactory factory = ImageProviderFactory.GetInstance();
            factory.LWidth = 300;
            factory.SavePath = "~" + TEM_FILEPATH + "image/";
            string url = "";
            string status = "1";
            try
            {
                ImageProvider provider = factory.UploadForThumbnail(file);
                url = provider.SavePath + provider.New_ImageName;
            }
            catch (Exception ex)
            {
                status = "0";
                LoggerFactory.GetErrorLogger().Error("文件上传失败!", ex);
            }
            Response.ClearContent();
            Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            Response.Write("{\"url\":\"" + url + "\",\"status\":" + status + "}");
            Response.End();
        }

        private class UpLoadImage
        {
            public int Id { get; set; }

            public string Url { get; set; }
        }
    }
}